package com.hotely5d.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hotely5d.dao.MemberMapper;
import com.hotely5d.dao.MessageMapper;
import com.hotely5d.entity.Member;
import com.hotely5d.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Transactional
public class MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MemberMapper memberMapper;

    public List<Message> findAll() {
        // 只查询未删除的留言
        return messageMapper.selectList(new EntityWrapper<Message>().eq("deleted", 0));
    }

    public Page<Message> search(Page<Message> page,Message message) {
        List<Message> list = messageMapper.selectPage(page, getEntityWrapper(message));
        for (Message m : list) {
            Member member = memberMapper.selectById(m.getMemberId());
            m.setMember(member);
        }
        return page.setRecords(list);
    }

    public List<Message> search(Message message) {
        return messageMapper.selectList(getEntityWrapper(message));
    }

    //条件构造器
    private EntityWrapper<Message> getEntityWrapper(Message message){
        EntityWrapper<Message> entityWrapper = new EntityWrapper<>();
        // 只查询未删除的留言
        entityWrapper.eq("deleted", 0);
        if(null != message){
            if(!StringUtils.isEmpty(message.getComment())){
                entityWrapper.like("comment",String.valueOf(message.getComment()));
            }
            if(!StringUtils.isEmpty(message.getReply())){
                entityWrapper.like("reply",String.valueOf(message.getReply()));
            }
        }
        entityWrapper.orderBy("create_time",false);
        return entityWrapper;
    }

    public void modify(Message message) {
        messageMapper.updateById(message);
    }

    public void add(Message message) {
        // 设置默认值：未删除
        message.setDeleted(0);
        messageMapper.insert(message);
    }

    public Message findById(Integer id) {
        // 只查询未删除的留言
        List<Message> messages = messageMapper.selectList(new EntityWrapper<Message>().eq("id", id).eq("deleted", 0));
        return messages.isEmpty() ? null : messages.get(0);
    }

    public void removeById(Integer id) {
        // 实现逻辑删除：将deleted字段设置为1
        Message message = new Message();
        message.setId(id);
        message.setDeleted(1);
        messageMapper.updateById(message);
    }

    /**
     * 导出留言数据到Excel
     */
    public void exportMessageData(HttpServletResponse response) throws IOException {
        // 查询所有留言数据
        List<Message> messageList = messageMapper.selectList(new EntityWrapper<Message>().orderBy("create_time", false));

        // 填充关联的用户信息
        for (Message message : messageList) {
            if (message.getMemberId() != null) {
                Member member = memberMapper.selectById(message.getMemberId());
                message.setMember(member != null ? member : new Member());
            }
        }

        // 创建工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("留言数据");

        // 创建标题样式
        CellStyle titleStyle = workbook.createCellStyle();
        Font titleFont = workbook.createFont();
        titleFont.setBold(true);
        titleFont.setFontHeightInPoints((short) 14);
        titleStyle.setFont(titleFont);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderTop(BorderStyle.THIN);
        titleStyle.setBorderBottom(BorderStyle.THIN);
        titleStyle.setBorderLeft(BorderStyle.THIN);
        titleStyle.setBorderRight(BorderStyle.THIN);

        // 创建数据样式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        dataStyle.setBorderTop(BorderStyle.THIN);
        dataStyle.setBorderBottom(BorderStyle.THIN);
        dataStyle.setBorderLeft(BorderStyle.THIN);
        dataStyle.setBorderRight(BorderStyle.THIN);
        dataStyle.setWrapText(true);

        // 创建状态样式
        CellStyle statusStyle = workbook.createCellStyle();
        statusStyle.cloneStyleFrom(dataStyle);
        Font statusFont = workbook.createFont();
        statusFont.setBold(true);
        statusStyle.setFont(statusFont);

        // 创建标题行
        Row titleRow = sheet.createRow(0);
        titleRow.setHeight((short) 500);

        String[] headers = {"ID", "用户姓名", "留言内容", "回复内容", "留言时间", "回复时间", "状态"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(titleStyle);
        }

        // 时间格式化
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 填充数据行
        for (int i = 0; i < messageList.size(); i++) {
            Message message = messageList.get(i);
            Row dataRow = sheet.createRow(i + 1);
            dataRow.setHeight((short) 400);

            // ID
            Cell cell0 = dataRow.createCell(0);
            cell0.setCellValue(message.getId() != null ? message.getId() : 0);
            cell0.setCellStyle(dataStyle);

            // 用户姓名
            Cell cell1 = dataRow.createCell(1);
            cell1.setCellValue(message.getMember() != null && message.getMember().getName() != null ?
                              message.getMember().getName() : "");
            cell1.setCellStyle(dataStyle);

            // 留言内容
            Cell cell2 = dataRow.createCell(2);
            cell2.setCellValue(message.getComment() != null ? message.getComment() : "");
            cell2.setCellStyle(dataStyle);

            // 回复内容
            Cell cell3 = dataRow.createCell(3);
            cell3.setCellValue(message.getReply() != null ? message.getReply() : "");
            cell3.setCellStyle(dataStyle);

            // 留言时间
            Cell cell4 = dataRow.createCell(4);
            cell4.setCellValue(message.getCreateTime() != null ?
                              dateFormat.format(message.getCreateTime()) : "");
            cell4.setCellStyle(dataStyle);

            // 回复时间
            Cell cell5 = dataRow.createCell(5);
            cell5.setCellValue(message.getReplyTime() != null ?
                              dateFormat.format(message.getReplyTime()) : "");
            cell5.setCellStyle(dataStyle);

            // 状态
            Cell cell6 = dataRow.createCell(6);
            String statusText = "";
            if (message.getStatus() != null) {
                statusText = message.getStatus() == 1 ? "待回复" : "已回复";
            }
            cell6.setCellValue(statusText);
            cell6.setCellStyle(statusStyle);
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
            // 设置最小列宽
            int currentWidth = sheet.getColumnWidth(i);
            sheet.setColumnWidth(i, Math.max(currentWidth, 3000));
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");

        String fileName = "留言数据_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date()) + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

        // 写入响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}
